package com.quanxi.qxaimain.common.globalException;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author lyx
 * @create 2022/9/2 15:12
 * 自定义异常
 */
@Slf4j
@RestControllerAdvice
public class ControllerExceptionAdvice {


    @ExceptionHandler({Exception.class})
    public ResponseVo exception(Exception e){
       // System.out.println(e.getMessage());
        StringBuffer sb =new StringBuffer();
        sb.append(e.getMessage());
        return new ResponseVo(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMsg(), sb.toString());
    }


    @ExceptionHandler({BindException.class})
    public ResponseVo MethodArgumentNotValidExceptionHandler(BindException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new ResponseVo(ResultCode.VALIDATE_ERROR.getCode(), ResultCode.VALIDATE_ERROR.getMsg(),objectError.getDefaultMessage());
    }


    //自定义抛出异常
    @ExceptionHandler(GlobalException.class)
    public ResponseVo GlobalException(GlobalException e) {
       // log.error(e.getMessage(), e);
        return new ResponseVo(e.getCode(), e.getMsg(), e.getMessage());
    }



}